package com.wayz.service;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.wayz.constants.PageVo;
import com.wayz.constants.ViewMap;
import com.wayz.entity.dto.poster.*;
import com.wayz.entity.pojo.poster.DPosterCategory;
import com.wayz.entity.pojo.poster.DPosterResolution;
import com.wayz.entity.pojo.poster.DPosterTemplet;
import com.wayz.entity.pojo.poster.DPosterTempletAdslot;
import com.wayz.entity.vo.poster.PosterCategoryVo;
import com.wayz.entity.vo.poster.PosterResolutionVo;
import com.wayz.entity.vo.poster.PosterTempletDetailVo;
import com.wayz.entity.vo.poster.PosterTempletVo;
import com.wayz.exception.WayzException;
import com.wayz.mapper.*;
import com.wayz.redis.BeanIdKeyEnum;
import com.wayz.redis.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

/**
 * 海报服务实现类
 *
 */
@Service("posterService")
@org.apache.dubbo.config.annotation.Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class PosterServiceImpl implements PosterService {

	/** DAO相关 */
	/** 海报类别DAO */
	@Resource(name = "dPosterCategoryDAO")
	private DPosterCategoryDAO dPosterCategoryDAO = null;
	/** 海报分辨率DAO */
	@Resource(name = "dPosterResolutionDAO")
	private DPosterResolutionDAO dPosterResolutionDAO = null;
	/** 海报模板DAO */
	@Resource(name = "dPosterTempletDAO")
	private DPosterTempletDAO dPosterTempletDAO = null;
	/** 海报分块配置模板DAO */
	@Resource(name = "dPosterTempletAdslotDAO")
	private DPosterTempletAdslotDAO dPosterTempletAdslotDAO = null;

	/** 对象相关 */
	@Resource(name = "redisUtils")
	private RedisUtils redisUtils;

	@Override
	public List<ViewMap> queryPosterResolutionView(Long myId, Long companyId) throws WayzException {
		return dPosterResolutionDAO.queryResolutionView();
	}

	@Override
	public PosterResolutionVo getPosterResolution(Long myId, Long id) throws WayzException {
		DPosterResolution dPosterResolution = dPosterResolutionDAO.get(id);
		PosterResolutionVo posterResolutionVo = new PosterResolutionVo();
		BeanUtils.copyProperties(dPosterResolution, posterResolutionVo);
		return posterResolutionVo;
	}

	@Override
	public PageVo<PosterResolutionVo> queryPosterResolution(Long myId, PosterResolutionPageDto posterResolutionPageDto) throws WayzException {
		// 初始化
		PageVo<PosterResolutionVo> page = new PageVo<>();
		List<PosterResolutionVo> posterList = new ArrayList<>();

		// 获取联屏广告以及数量
		Integer totalCount = dPosterResolutionDAO.count(posterResolutionPageDto.getWidth(), posterResolutionPageDto.getHeight());
		if (totalCount <= 0) {
			return page;
		}
		List<DPosterResolution> list = dPosterResolutionDAO.query(posterResolutionPageDto.getWidth(), posterResolutionPageDto.getHeight()
				, posterResolutionPageDto.getStartIndex(), posterResolutionPageDto.getPageSize());
		page.setTotalCount(totalCount);
		PosterResolutionVo posterResolutionVo;
		if (!list.isEmpty()) {
			for (DPosterResolution dPosterResolution : list) {
				posterResolutionVo = new PosterResolutionVo();
				BeanUtils.copyProperties(dPosterResolution, posterResolutionVo);
				posterList.add(posterResolutionVo);
			}
		}

		page.setList(posterList);

		// 返回数据
		return page;
	}

	@Override
	public Long createPosterResolution(Long myId, PosterResolutionDto posterResolutionDto)
			throws WayzException {
		// 分辨率名称
		Integer width = posterResolutionDto.getWidth();
		Integer height = posterResolutionDto.getHeight();
		String name = width + "*" + height;

		// 校验该分辨率是否存在
		if (dPosterResolutionDAO.existsName(name, null)) {
			throw new WayzException("该分辨率已存在!");
		}

		// 创建
		Long id = redisUtils.incrBy(BeanIdKeyEnum.POSTER_RESOLUTION.getKey(), RedisUtils.STEP_SIZE);
		DPosterResolution create = new DPosterResolution();
		create.setId(id);
		create.setName(width + "*" + height);
		create.setWidth(width);
		create.setHeight(height);
		create.setSort(posterResolutionDto.getSort());
		create.setCreatorId(myId);
		dPosterResolutionDAO.create(create);

		// 返回结果
		return id;
	}

	@Override
	public void deletePosterResolution(Long myId, Long companyId, Long id) throws WayzException {
		// 校验分辨率是否存在
		DPosterResolution dResolution = dPosterResolutionDAO.get(id);
		if (dResolution == null) {
			throw new WayzException("分辨率不存在!");
		}

		Integer integer = dPosterResolutionDAO.countPosterTempletByResolutionId(id);
		if (integer > 0) {
			throw new WayzException("有" + integer + "个海报使用此分辨率，无法删除");
		}

		// 删除数据
		dPosterResolutionDAO.delete(id);
	}

	@Override
	public List<PosterCategoryVo> queryPosterCategory(Long myId, Long companyId, Long id) throws WayzException {

		List<PosterCategoryVo> categoryList = new ArrayList<>();
		List<DPosterCategory> list = dPosterCategoryDAO.query(id);
		PosterCategoryVo posterCategoryVo;
		if (!list.isEmpty()) {
			for (DPosterCategory dPosterCategory : list) {
				posterCategoryVo = new PosterCategoryVo();
				BeanUtils.copyProperties(dPosterCategory, posterCategoryVo);
				categoryList.add(posterCategoryVo);
			}
		}
		return categoryList;
	}

	@Override
	public Long createPosterCategory(Long myId, PosterCategoryDto posterCategoryDto) throws WayzException {
		String name = posterCategoryDto.getName();
		// 校验海报类别名称是否存在
		if (dPosterCategoryDAO.existsName(name, null)) {
			throw new WayzException("该海报类别名称已存在!");
		}

		// 创建
		Long id = redisUtils.incrBy(BeanIdKeyEnum.POSTER_CATEGORY.getKey(), RedisUtils.STEP_SIZE);
		DPosterCategory create = new DPosterCategory();
		create.setId(id);
		create.setName(name);
		create.setDescription(posterCategoryDto.getDescription());
		create.setCreatorId(myId);
		dPosterCategoryDAO.create(create);

		// 返回标识
		return id;
	}

	@Override
	public void modifyPosterCategory(Long myId, PosterCategoryDto posterCategoryDto)
			throws WayzException {

		Long id = posterCategoryDto.getId();
		String name = posterCategoryDto.getName();

		// 校验海报类别是否存在
		DPosterCategory dCategory = dPosterCategoryDAO.get(id);
		if (dCategory == null) {
			throw new WayzException(MessageFormat.format("海报类别不存在，海报类别标识：{0}", id));
		}

		// 校验海报类别名称是否存在
		if (dPosterCategoryDAO.existsName(name, id)) {
			throw new WayzException("该海报类别名称已存在!");
		}

		// 修改海报类别信息
		DPosterCategory modify = new DPosterCategory();
		modify.setId(id);
		modify.setName(name);
		modify.setDescription(posterCategoryDto.getDescription());
		dPosterCategoryDAO.modify(modify);
	}

	@Override
	public void deletePosterCategory(Long myId, Long id) throws WayzException {
		// 校验海报类别是否存在
		DPosterCategory dCategory = dPosterCategoryDAO.get(id);
		if (dCategory == null) {
			throw new WayzException(MessageFormat.format("海报类别不存在，海报行业标识：{0}", id));
		}
		
		Integer integer = dPosterCategoryDAO.countPosterTempletByCategoryId(id);
		if (integer > 0) {
			throw new WayzException("有" + integer + "个海报使用此海报行业，无法删除");
		}

		// 设置海报类别为删除状态
		DPosterCategory modify = new DPosterCategory();
		modify.setId(id);
		modify.setIsDeleted(true);
		dPosterCategoryDAO.modify(modify);
	}

	@Override
	public PageVo<PosterTempletVo> queryPosterTemplet(Long myId, PosterTempletPageDto posterTempletPageDto) {
		// 初始化
		PageVo<PosterTempletVo> page = new PageVo<>();
		List<PosterTempletVo> list = new ArrayList<>();

		// 获取海报模板以及数量
		Integer totalCount = dPosterTempletDAO.count(null, posterTempletPageDto.getName(), posterTempletPageDto.getResolutionId(),
				posterTempletPageDto.getCategoryId(), posterTempletPageDto.getIsPublish());
		if (totalCount <= 0) {
			return page;
		}
		List<DPosterTemplet> templetList = dPosterTempletDAO.query(null, posterTempletPageDto.getName(), posterTempletPageDto.getResolutionId(),
				posterTempletPageDto.getCategoryId(), posterTempletPageDto.getIsPublish(), posterTempletPageDto.getStartIndex(), posterTempletPageDto.getPageSize());

		PosterTempletVo posterTempletVo;
		if (!templetList.isEmpty()) {
			for (DPosterTemplet dPosterTemplet : templetList) {
				posterTempletVo = new PosterTempletVo();
				BeanUtils.copyProperties(dPosterTemplet, posterTempletVo);
				list.add(posterTempletVo);
			}
		}

		// 赋值
		page.setList(list);
		page.setTotalCount(totalCount);

		// 返回数据
		return page;
	}

	@Override
	public List<ViewMap> queryPosterTempletView(Long myId, Long companyId) throws WayzException {
		// 初始化
		List<ViewMap> viewList = dPosterTempletDAO.queryPosterTempletView(null);

		// 返回数据
		return viewList;
	}

	@Override
	public void createPosterTemplet(Long myId, PosterTempletDto posterTempletDto) throws WayzException {

		String name = posterTempletDto.getName();
		Long resolutionId = posterTempletDto.getResolutionId();
		List<PosterTempletAdslotDto> adslotList = posterTempletDto.getAdslotList();

		// 校验名称唯一
		if (dPosterTempletDAO.queryUnique(null, name, null)) {
			throw new WayzException(MessageFormat.format("海报模板名称已存在--海报模板名称:{0}", name));
		}
		// 校验分辨率存在
		if (dPosterResolutionDAO.get(resolutionId) == null) {
			throw new WayzException(MessageFormat.format("海报分辨率标识不存在--海报分辨率标识:{0}", resolutionId));
		}
		
		// 验证参数
		if(adslotList != null && adslotList.size() <= 0){
			throw new WayzException("请添加图片或文字！");
		}
				
		// 创建
		Long id = redisUtils.incrBy(BeanIdKeyEnum.POSTER_TEMPLET.getKey(), RedisUtils.STEP_SIZE);
		DPosterTemplet create = new DPosterTemplet();
		create.setId(id);
		create.setCategoryId(posterTempletDto.getCategoryId());
		create.setCompanyId(posterTempletDto.getCompanyId());
		create.setName(name);
		create.setPreviewUrl(posterTempletDto.getPreviewUrl());
		create.setBackground(posterTempletDto.getBackground());
		create.setResolutionId(resolutionId);
		dPosterTempletDAO.create(create);

		// 添加海报分块配置信息
		createTempletAdslot(adslotList, id);
	}

	/**
	 * 创建海报分块配置信息
	 * 
	 * @param adslotList
	 * @throws WayzException
	 */
	public void createTempletAdslot(List<PosterTempletAdslotDto> adslotList, Long id) throws WayzException {
		if (adslotList != null && adslotList.size() > 0) {
			for (PosterTempletAdslotDto create : adslotList) {
				create.setPosterTempletId(id);
				DPosterTempletAdslot dPosterTempletAdslot = new DPosterTempletAdslot();
				BeanUtils.copyProperties(create, dPosterTempletAdslot);
				dPosterTempletAdslotDAO.create(dPosterTempletAdslot);
			}
		}
	}

	@Override
	public void modifyPosterTemplet(Long myId, PosterTempletDto posterTempletDto)
			throws WayzException {

		Long id = posterTempletDto.getId();
		String name = posterTempletDto.getName();
		Long resolutionId = posterTempletDto.getResolutionId();
		List<PosterTempletAdslotDto> adslotList = posterTempletDto.getAdslotList();

		DPosterTemplet dPlayTemplet = dPosterTempletDAO.get(id);
		if (dPlayTemplet == null) {
			throw new WayzException(MessageFormat.format("海报模板不存在--海报模板标识:{0}", id));
		}
		// 校验名称唯一
		if (dPosterTempletDAO.queryUnique(null, name, id)) {
			throw new WayzException(MessageFormat.format("海报模板名称已存在--海报模板名称:{0}", name));
		}
		// 校验分辨率存在
		if (dPosterResolutionDAO.get(resolutionId) == null) {
			throw new WayzException(MessageFormat.format("海报分辨率标识不存在--海报分辨率标识:{0}", resolutionId));
		}
		// 验证参数
		if(adslotList != null && adslotList.size() <= 0){
			throw new WayzException("请添加图片或文字！");
		}

		// 修改基础信息
		DPosterTemplet modify = new DPosterTemplet();
		modify.setId(id);
		modify.setCategoryId(posterTempletDto.getCategoryId());
		modify.setCompanyId(posterTempletDto.getCompanyId());
		modify.setName(name);
		modify.setPreviewUrl(posterTempletDto.getPreviewUrl());
		modify.setBackground(posterTempletDto.getBackground());
		modify.setResolutionId(resolutionId);
		dPosterTempletDAO.modify(modify);

		// 删除已有的海报分块配置信息
		dPosterTempletAdslotDAO.delete(id, null);

		// 添加海报分块配置信息
		createTempletAdslot(adslotList, id);
	}
	
	/**
	 *  更新海报模板发布状态
	 * 
	 * @param myId 我的标识
	 * @param id 模板标识
	 * @param isPublish 是否发布
	 * @throws WayzException 平台异常
	 */
	@Override
	public void updatePosterTempletStatus(Long myId, Long id, Boolean isPublish)throws WayzException {
		dPosterTempletDAO.updatePosterTempletStatus(id, isPublish);
	}
	
	/**
	 *  更新海报模板所属公司
	 * 
	 * @param myId 我的标识
	 * @param id 模板标识
	 * @param companyId 所属公司
	 * @throws WayzException 平台异常
	 */
	@Override
	public void updatePosterCompanyIdByTempletId(Long myId, Long id, Long companyId)throws WayzException {
		dPosterTempletDAO.updatePosterCompanyIdByTempletId(id, companyId);
	}

	@Override
	public void deletePosterTemplet(Long myId, Long id) throws WayzException {
		// 验证模板是否存在
		DPosterTemplet dPlayTemplet = dPosterTempletDAO.get(id);
		if (dPlayTemplet == null) {
			throw new WayzException(MessageFormat.format("海报模板不存在--海报模板标识:{0}", id));
		}
		// 删除
		dPosterTempletDAO.updateDelete(id);
	}

	@Override
	public PosterTempletDetailVo getPosterTempletDetail(Long myId, Long templetId) throws WayzException {
		// 初始化
		PosterTempletDetailVo detail = null;

		// 获取模板信息
		DPosterTemplet dPlayTemplet = dPosterTempletDAO.get(templetId);
		if (dPlayTemplet != null) {
			detail = new PosterTempletDetailVo();

			// 设置参数
			detail.setId(dPlayTemplet.getId());
			detail.setCompanyId(dPlayTemplet.getCompanyId());
			detail.setCategoryName(dPlayTemplet.getCompanyName());
			detail.setResolutionId(dPlayTemplet.getResolutionId());
			detail.setResolutionName(dPlayTemplet.getResolutionName());
			detail.setCategoryId(dPlayTemplet.getCategoryId());
			detail.setCategoryName(dPlayTemplet.getCategoryName());
			detail.setName(dPlayTemplet.getName());
			detail.setPreviewUrl(dPlayTemplet.getPreviewUrl());
			detail.setDescription(dPlayTemplet.getDescription());
			detail.setBackground(dPlayTemplet.getBackground());
			detail.setCreatedTime(dPlayTemplet.getCreatedTime());
			detail.setModifiedTime(dPlayTemplet.getModifiedTime());

			// 查询海报模板分块配置信息
			List<DPosterTempletAdslot> adslotList = dPosterTempletAdslotDAO.query(templetId);
			if (adslotList != null && adslotList.size() > 0) {
				detail.setAdslotList(adslotList);
			}
		}
		else {
			throw new WayzException(MessageFormat.format("海报模板不存在--海报模板标识:{0}", templetId));
		}

		// 返回数据
		return detail;
	}

}
